﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class LangresController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        // GET: Manage/Role
        [AuthorizeFilter("Manage.LangRes")]
        public ActionResult List()
        {
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();

            //编辑权限
            ViewBag.CanEdit = UserAuthBLL.HasAuth("Manage.LangRes.Edit");

            //获取页面状态
            var pageState = Session["Manage.LangRes.PageState"] as PageStateModel;
            if (pageState == null)
                pageState = new PageStateModel
                {
                    page = 1,
                    rows = 20,
                    sort = "Id",
                    order = "asc"
                };

            //页面状态
            ViewBag.PageState = pageState;

            //查询条件
            ViewBag.Searchkey = Utils.NvStr(pageState.queryParams["s"]);

            //语言选项
            ViewBag.LangList = CommonStr.GetLangSelectList("zh_cn");
            //资源分类
            ViewBag.RescategoryList = new SelectList(new S_lang_resService().DistinctRescategory());

            return View();
        }

        [AuthorizeFilter("Manage.LangRes")]
        public JsonResult LangResListJson(int page, int rows, string s, string lang, string rescategory, string sort, string order)
        {

            #region 保存页面状态

            PageStateModel pageState = new PageStateModel
            {
                page = page,
                rows = rows,
                sort = sort,
                order = order
            };
            pageState.queryParams["lang"] = lang;
            pageState.queryParams["rescategory"] = rescategory;
            pageState.queryParams["s"] = s;

            Session.Add("Manage.LangRes.PageState", pageState);
            #endregion

            S_lang_resService langservice = new S_lang_resService();

            int rowscount = 0;

            var list = langservice.PageList(page, rows, s, lang, rescategory, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Lang,
                p.Resname,
                p.Reskey,
                p.Rescategory,
                p.Rescontent,
                p.Resjs,
                Updatetime = CommonStr.GetDateTimeStr(p.Updatetime)
            });

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        #endregion

        #region 删除

        [AuthorizeFilter("Manage.LangRes")]
        public JsonResult Delete(string ids)
        {
            try
            {
                new S_lang_resService().DeleteByIds(ids);

                //清缓存
                 new S_lang_resService().ClearCache();

                 return Json(new AjaxResult("0", CSMSLang.Get("message_delete_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 保存

        [AuthorizeFilter("Manage.LangRes")]
        public JsonResult Save(string jsondata)
        {
            try
            {
                var langservice = new S_lang_resService();

                //序列化Json数据
                LangResEditModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<LangResEditModel>(jsondata);

                //保存
                langservice.Save(model);

                //清缓存
                langservice.ClearCache();

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 编辑/查看

        [AuthorizeFilter("Manage.LangRes")]
        // GET: Manage/Role/Edit/5
        public ActionResult Edit(int id)
        {
            var langservice = new S_lang_resService();
            var langlist = CommonStr.GetLangSelectList().Select(p => new
            {
                Key = p.Value,
                Name = p.Text
            }).ToList();

            //资源分类
            ViewBag.RescategoryList = new SelectList(new S_lang_resService().DistinctRescategory());

            if (id == 0)
            {
                var model = new LangResEditModel();
                model.Resjs = 0;
                model.ContentList = langlist.Select(p => new LangResItem
                {
                    Lang = p.Key,
                    Langname = p.Name,
                    Content = ""
                }).ToList();

                return View(model);
            }
            else
            {
                var lang = langservice.Find(id);
                var model = new LangResEditModel
                {
                    Id = id,
                    Rescategory = lang.Rescategory,
                    Resname = lang.Resname,
                    Reskey = lang.Reskey,
                    Resjs = lang.Resjs
                };

                model.ContentList = langservice.ListByReskey(lang.Reskey).Select(p => new LangResItem
                {
                    Lang = p.Lang,
                    Langname = langlist.Where(g => g.Key == p.Lang).Any() ? langlist.Where(g => g.Key == p.Lang).First().Name : p.Lang,
                    Content = p.Rescontent
                }).ToList();

                foreach (var item in langlist)
                {
                    if (!model.ContentList.Where(p => item.Key.Equals(p.Lang, StringComparison.OrdinalIgnoreCase)).Any())
                    {
                        model.ContentList.Add(new LangResItem
                        {
                            Lang = item.Key,
                            Langname = item.Name,
                            Content = ""
                        });
                    }
                }

                return View(model);
            }
        }

        #endregion

        #region 重复验证

        [IgnoreAuthorizeFilter]
        public string ExsitCheck(int id, string reskey)
        {
            return new S_lang_resService().Exist(id, reskey) ? "no" : "yes";
        }

        #endregion

        #region 下载JS资源

        [IgnoreAuthorizeFilter]
        public ActionResult Down()
        {
            var lang = Request.QueryString["lang"];
            var list = new S_lang_resService().ListByLang(lang).Where(p => p.Resjs == 1);

            var result = new Dictionary<string, string>();
            foreach (var item in list)
            {
                result.Add(item.Reskey, item.Rescontent);
            }

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            json = "var csms_lang = " + json + ";";
            byte[] rawData = System.Text.Encoding.UTF8.GetBytes(json);

            return File(rawData, "application/json", "csms.resouces." + lang + ".js");
        }

        #endregion

        #region 生成服务器文件

        [IgnoreAuthorizeFilter]
        public JsonResult GenJs()
        {
            try
            {
                var path = Server.MapPath("/scripts/app/");

                //简体
                var list = new S_lang_resService().ListByLang("zh_cn").Where(p => p.Resjs == 1);

                var result = new Dictionary<string, string>();
                foreach (var item in list)
                {
                    result.Add(item.Reskey, item.Rescontent);
                }

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                json = "var csms_lang = " + json + ";";
                using (var sr = new System.IO.StreamWriter(path + "csms.resouces.zh_cn.js", false, System.Text.Encoding.UTF8))
                {
                    sr.Write(json);
                }


                //繁体
                var list_zh_hk = new S_lang_resService().ListByLang("zh_hk").Where(p => p.Resjs == 1);

                var result_zh_hk = new Dictionary<string, string>();
                foreach (var item in list_zh_hk)
                {
                    result_zh_hk.Add(item.Reskey, item.Rescontent);
                }

                var json_zh_hk = Newtonsoft.Json.JsonConvert.SerializeObject(result_zh_hk);
                json_zh_hk = "var csms_lang = " + json_zh_hk + ";";
                using (var sr = new System.IO.StreamWriter(path + "csms.resouces.zh_hk.js", false, System.Text.Encoding.UTF8))
                {
                    sr.Write(json_zh_hk);
                }

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

    }
}